import { resolve } from "path";
import { UserConfigExport, ConfigEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { loadEnv } from "./build/utils";
import { createProxy } from "./build/proxy";
import { viteMockServe } from "vite-plugin-mock";
import styleImport from "vite-plugin-style-import";

// 获取指定目录的绝对路径
const pathResolve = (dir: string): any => {
  return resolve(__dirname, ".", dir);
};
/**
 * @param VITE_PORT 默认端口号
 * @param VITE_PUBLIC_PATH 默认公共资源路径
 * @param VITE_PROXY 代理配置
 * @param VITE_OPEN 项目启动后是否自动打开浏览器
 */
const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_OPEN } = loadEnv();
// 定义路径映射规则
const alias: Record<string, string> = {
  "/@": pathResolve("src"),
  //解决开发环境下的警告 You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
  "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js",
};

// 当前工作目录
const root: string = process.cwd();

export default ({ command }: ConfigEnv): UserConfigExport => {
  let prodMock = true;
  return {
    /**
     * 基本公共路径
     * 可根据项目部署域名的后缀自行填写
     * @default '/'
     */
    base:process.env.NODE_ENV === "production" ? "/" : VITE_PUBLIC_PATH,
    // 项目根目录，即index.html所在目录
    root,
    // 配置文件系统路径别名
    resolve: {
      alias,
    },
    // 服务端渲染
    server: {
      // 是否开启 https
      https: false,
      /**
       * 端口号
       * @default 3000
       */
      port: VITE_PORT,
      // 本地跨域代理
      proxy: createProxy(VITE_PROXY),
      // 项目启动后是否自动打开浏览器
      open:VITE_OPEN
    },
    // 配置插件
    plugins: [
      vue(),
      vueJsx(),
      styleImport({
        libs: [
          // 按需加载element-plus
          {
            libraryName: "element-plus",
            esModule: true,
            ensureStyleFile: true,
            resolveStyle: (name) => {
              return `element-plus/lib/theme-chalk/${name}.css`;
            },
            resolveComponent: (name) => {
              return `element-plus/lib/${name}`;
            },
          },
          // 按需加载vxe-table
          {
            libraryName: "vxe-table",
            esModule: true,
            resolveComponent: (name) => `vxe-table/es/${name}`,
            resolveStyle: (name) => `vxe-table/es/${name}/style.css`,
          },
        ],
      }),
        // 配置mock数据服务
      viteMockServe({
        mockPath: "mock",
        localEnabled: command === "serve",
        prodEnabled: command !== "serve" && prodMock,
        injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `,
        logger: true,
      }),
    ],
    // 打包配置
    build: {
      brotliSize: false,
      // 消除打包大小超过500kb警告
      chunkSizeWarningLimit: 2000,
    },
    // 定义全局变量替换方式，在开发环境中其中的每一项会被定义在全局，在生产环境会被静态替换
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
    },
  };
};
